<?php
if(!defined('IN_BSTO')){ die('[ERROR] You cannot load this page directly !!!'); }

Class RegisterController Extends BaseController {
	private $errorList = array();
	private $valueList = array();
	private $filters = array
	(
	  "username" => array
		(
	    "filter"=>FILTER_VALIDATE_REGEXP,
		"options"=> array
			(
				"regexp"=>"/^[a-zA-Z][a-zA-Z0-9]*/",
			)
		),	  	  
	  "email"=> FILTER_VALIDATE_EMAIL,
	  "avatar"=> FILTER_VALIDATE_URL,
	);
	
	function __construct($registry)
	{
		parent::__construct($registry);
		$this->errorList['username'] = '';
		$this->errorList['password1'] = '';
		$this->errorList['password2'] = '';
		$this->errorList['email'] = '';
		$this->errorList['phone'] = '';
		$this->errorList['company'] = '';
		$this->errorList['address'] = '';
		$this->errorList['terms'] = '';
		$this->errorList['logout'] = '';
		$this->valueList['more_field'] = '';
		$this->valueList['value_email'] = '';
		$this->valueList['disabled'] = '';
		$this->valueList['ignore'] = '';
		$this->valueList['value_username'] = '';
		$this->valueList['value_phone'] = '';
		$this->valueList['value_company'] = '';
		$this->valueList['value_address'] = '';
	}
	private function clean_entities($fragment)
	{
		$translite_simbols = array ( 
			'#(Ã |Ã¡|áº¡|áº£|Ã£|Ã¢|áº§|áº¥|áº­|áº©|áº«|Äƒ|áº±|áº¯|áº·|áº³|áºµ)#', 
			'#(Ã¨|Ã©|áº¹|áº»|áº½|Ãª|á»�|áº¿|á»‡|á»ƒ|á»…)#', 
			'#(Ã¬|Ã­|á»‹|á»‰|Ä©)#', 
			'#(Ã²|Ã³|á»�|á»�|Ãµ|Ã´|á»“|á»‘|á»™|á»•|á»—|Æ¡|á»�|á»›|á»£|á»Ÿ|á»¡)#', 
			'#(Ã¹|Ãº|á»¥|á»§|Å©|Æ°|á»«|á»©|á»±|á»­|á»¯)#', 
			'#(á»³|Ã½|á»µ|á»·|á»¹)#', 
			'#(Ä‘)#', 
			'#(Ã€|Ã�|áº |áº¢|Ãƒ|Ã‚|áº¦|áº¤|áº¬|áº¨|áºª|Ä‚|áº°|áº®|áº¶|áº²|áº´)#', 
			'#(Ãˆ|Ã‰|áº¸|áºº|áº¼|ÃŠ|á»€|áº¾|á»†|á»‚|á»„)#', 
			'#(ÃŒ|Ã�|á»Š|á»ˆ|Ä¨)#', 
			'#(Ã’|Ã“|á»Œ|á»Ž|Ã•|Ã”|á»’|á»�|á»˜|á»”|á»–|Æ |á»œ|á»š|á»¢|á»ž|á» )#', 
			'#(Ã™|Ãš|á»¤|á»¦|Å¨|Æ¯|á»ª|á»¨|á»°|á»¬|á»®)#', 
			'#(á»²|Ã�|á»´|á»¶|á»¸)#', 
			'#(Ä�)#', 
			) ;

		$replace = array ( 
			'a', 
			'e', 
			'i', 
			'o', 
			'u', 
			'y', 
			'd', 
			'A', 
			'E', 
			'I', 
			'O', 
			'U', 
			'Y', 
			'D',  
		) ; 
		$fragment = preg_replace($translite_simbols, $replace, $fragment); 
		
		return $fragment;
	}
	
	private function clean()
	{
		$cleaned_data = filter_input_array(INPUT_POST, $this->filters);
		if (!$cleaned_data['username']) {
			$this->errorList['username'] = 'Please choose an valid username.<br/>';
		}
		if (!$cleaned_data['email']) {
			$this->errorList['email'] = 'Please use a valid email format.<br/>';
		}
		if ($_POST['password1'] == '') {
			$this->errorList['password1'] = 'Please enter your password.<br/>';
		}
		if ($_POST['password2'] == '') {
			$this->errorList['password2'] = 'Please confirm your password.<br/>';
		}		
		if (!isset($_POST['terms'])) {
			$this->errorList['terms'] = 'Please accept terms of use to register.<br/>';
		}
		if (isset($_POST['avatar'])) {
			if ($_POST['avatar'] != '' && !$cleaned_data['avatar']) {
				$this->errorList['avatar'] = 'Invalid avatar.';
			}
		}
		/*foreach($this->errorList as $key=>$value)
		{
			$method = 'clean'.$key;
			if(is_callable($method)){
				$this->$method();
			}
		}*/
		$this->clean_username();
		$this->clean_email();
		$this->clean_password2();
	}
	
	private function clean_username()
	{
		//global $bsto;
		try {
			//echo "Enter clean user";
			$this->registry->db->get('userManager')->get('username', trim($_POST['username']));
			$this->errorList['username'] = 'This name has been used.<br/>';
		}
		catch (Exception $e) {			
			
		}
	}
	
	private function clean_email()
	{
		//global $bsto;
		try {
			$this->registry->db->get('userManager')->get('email', $_POST['email']);
			$this->errorList['email'] = 'This e-mail has been used.<br/>';
		}
		catch (Exception $e) {
			
		}
	}
	
	private function clean_password2()	
	{	
		//echo "Enter pass";			
		if ( ($_POST['password2'] != '') && ($_POST['password2'] != $_POST['password1']) ) {
			$this->errorList['password2'] = 'Passwords did not match.<br/>';
		}
	}
	
	private function is_valid()
	{
		foreach ( $this->errorList as $key => $value )
		{
			if ( $value != '' ) {
				return FALSE;
			}
		}
		return TRUE;
	}
	
	private function get_post_info()
	{
		$this->valueList['value_username'] = isset($_POST['username'])? $_POST['username']:'';
		$this->valueList['value_email'] = isset($_POST['email'])? $_POST['email']:'';
		$this->valueList['value_phone'] = isset($_POST['phone'])? $_POST['phone']:'';
		$this->valueList['value_company'] = isset($_POST['company'])? $_POST['company']:'';
		$this->valueList['value_address'] = isset($_POST['address'])? $_POST['address']:'';		
	}
	
	public function index() 
    {
    	
    	$method = $_SERVER['REQUEST_METHOD'];   
    	$currentUser = $this->registry->db->get('userManager')->getCurrentUser(); 	
    	if($currentUser){
    		$this->errorList['logout'] = 'Please logout before register a new user.';
    	}
    	if ($method=='POST'){      		       
            $this->clean();    
            
            if($this->is_valid()) {            	            	
            	if ($currentUser == NULL) {
	            	if(!isset($_POST['fbid'])){
		            	$_POST['fbid'] = '';
		            }
		    		if(!isset($_POST['fullname'])){
		            	$_POST['fullname'] = '';
		            }
		    		if(!isset($_POST['avatar'])){
		            	$_POST['avatar'] = '';
		            }
	            	$manager = $this->registry->db->get('userManager');
	            	$newUser = $manager->create($_POST['username'], $_POST['password1'], $_POST['email'], $_POST['phone'], $_POST['company'], $_POST['address'], 1, 'Normal', $_POST['fbid'], $_POST['fullname'], $_POST['avatar']);
	            	//echo($_POST['fullname']);
	           		header("Location: ". BSTO_ROOT_PATH);
            	} else {
            		//$this->errorList['logout'] = 'Please logout before register a new user.';
            		$content = $this->registry->template->getTemplate('registerForm', $this->errorList, 'Module');
    				echo $this->registry->template->getPageContent('index', 'Register', $content, array('bstoHead'=>""));
            	}
          	} else {
          		$this->get_post_info();          		
          	
            	$content = $this->registry->template->getTemplate('registerForm', array_merge($this->errorList, $this->valueList), 'Module');
    			echo $this->registry->template->getPageContent('index', 'Register', $content, array('bstoHead'=>""));
            }
    	}
    	else { 
    		$this->get_post_info();
	    	
    		$content = $this->registry->template->getTemplate('registerForm', array_merge($this->errorList, $this->valueList), 'Module');
            
            $this->registry->template->setMenuKey('register');
            $tags = array('bstoHead'=>"");
	    	$user = $this->registry->db->get('userManager')->getCurrentUser();
	        if($user != null){
	        	$tags['login'] = '<li id="login"><span> Hello, '. $user->get('username').'</span><a href="{bstoRootPath}logout">Logout</a></li>';	
	        }else{
	        	$tags['login'] = '<li id="login"><a href="{bstoRootPath}login">Login</a></li>';
	        }
    		echo $this->registry->template->getPageContent('index', 'Register', $content, $tags);
			
    	}
    	
    }
    //private function validateRequired()

}
?>